#include <Constants.au3>
#include <Math.au3>
#Include <Timers.au3>
#NoTrayIcon

Opt("TrayMenuMode",1)   ; Default tray menu items (Script Paused/Exit) will not be shown.

Dim Const $max_depots = 100
Dim $depot[100]
Dim $depot_count, $poll_interval, $client

Func ReadINI()
	$poll_interval = IniRead("p4notifier.ini", "settings", "PollInterval", "60000")
	If $poll_interval < 60000 Then $poll_interval = 60000
	$client = IniRead("p4notifier.ini", "settings", "ClientSpec", "invalid")
	;MsgBox(4096, $poll_interval, $client)
	$depot_count = Int(IniRead("p4notifier.ini", "depots", "Count", 0))
	;MsgBox(4096, String($depot_count), String($depot_count))

	For $i = 0 to _Min($max_depots, $depot_count) - 1
		$depot[$i] = IniRead("p4notifier.ini", "depots", String($i), "invalid_depot")
		;MsgBox(4096, String($i), $depot[$i])
	Next
EndFunc

ReadINI()

$check_now_item = TrayCreateItem("Check now")
$reread_ini = TrayCreateItem("Reread .ini")
$sync = TrayCreateItem("Sync")
TrayCreateItem("")
$exit_item = TrayCreateItem("Exit")

TraySetState()
TraySetIcon("TrayIcon_UpToDate.ico")

Func CheckDepots()
	Local $changed=""
	For $i = 0 to _Min($max_depots, $depot_count) - 1
		Local $foo = Run("p4 -c " & $client & " sync -n " & $depot[$i], ".", 0, $STDERR_CHILD + $STDOUT_CHILD)

		Local $result="", $error=""
		While 1
			$result &= StdoutRead($foo)
			If @error Then ExitLoop
		Wend

		While 1
			$error &= StderrRead($foo)
			If @error Then ExitLoop
		Wend		

		If $result <> "" Then
			$changed &= $depot[$i] & @LF
		EndIf
		;MsgBox(4096, $result, $error)
	Next
	
	If $changed <> "" Then
		TraySetIcon("TrayIcon_NeedUpdate.ico")
		TrayTip("Changed depots", $changed, 10)
	Else
		TraySetIcon("TrayIcon_UpToDate.ico")
	EndIf
EndFunc

Func Sync()
	Local $synced=""
	For $i = 0 to _Min($max_depots, $depot_count) - 1
		Local $foo = Run("p4 -c " & $client & " sync " & $depot[$i] & "#head", ".", 0, $STDERR_CHILD + $STDOUT_CHILD)

		Local $result="", $error=""
		While 1
			$result &= StdoutRead($foo)
			If @error Then ExitLoop
		Wend

		While 1
			$error &= StderrRead($foo)
			If @error Then ExitLoop
		Wend		

		If $error == "" Then
			$synced &= $depot[$i] & @LF
		EndIf
		;MsgBox(4096, $result, $error)
	Next
	
	If $synced <> "" Then
		TrayTip("Synced depots", $synced, 10)
		CheckDepots()
	EndIf
EndFunc

Func TimerCheckDepots($hWnd, $Msg, $iIDTimer, $dwTime)
	#forceref $hWnd, $Msg, $iIDTimer, $dwTime
	CheckDepots()
EndFunc

_Timer_SetTimer(GUICreate("p4notifier"), $poll_interval, "TimerCheckDepots")

While 1
    $msg = TrayGetMsg()
    Select
		Case $msg = 0			
			ContinueLoop
        Case $msg = $check_now_item
            CheckDepots()
		Case $msg = $reread_ini
			ReadINI()
			CheckDepots()
		Case $msg = $sync
			Sync()
        Case $msg = $exit_item
            ExitLoop
    EndSelect
	
WEnd

_Timer_KillAllTimers($check_now_item)
GUIDelete()
